using System.Web.Mvc;
using Appetite.Domain.Models;
using Appetite.Domain.Repository;
using Appetite.Presentation.Web.Model.Recipe;

namespace Appetite.Presentation.Web.Controllers
{
    public class RecipeController : CustomController
    {
        private readonly IRecipeRepository _recipeRepository;
        private readonly IRecipeCategoryRepository _recipeCategoryRepository;

        public RecipeController(IRecipeRepository recipeRepository, IRecipeCategoryRepository recipeCategoryRepository)
        {
            _recipeRepository = recipeRepository;
            _recipeCategoryRepository = recipeCategoryRepository;
        }

        [OutputCache(Duration = 30)]
        public ViewResult Index()
        {
            return View(_recipeRepository.All);
        }

        public ViewResult Details(System.Guid id)
        {
            return View(_recipeRepository.Find(id));
        }

        [OutputCache(Duration = 30)]
        public ActionResult Create()
        {
            var viewModel = new CreateOrEditViewModel();
            viewModel.Recipe = new Recipe();
            viewModel.Categories = new SelectList(_recipeCategoryRepository.All, "Id", "Name", viewModel.Recipe.RecipeCategoryId);
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Create(CreateOrEditViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                _recipeRepository.InsertOrUpdate(viewModel.Recipe);
                _recipeRepository.Save();
                return RedirectToAction("Index");
            }

            return View();
        }

        public ActionResult Edit(System.Guid id)
        {
            var viewModel = new CreateOrEditViewModel();
            viewModel.Recipe = _recipeRepository.Find(id);
            viewModel.Categories = new SelectList(_recipeCategoryRepository.All, "Id", "Name", viewModel.Recipe.RecipeCategoryId);
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(CreateOrEditViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                _recipeRepository.InsertOrUpdate(viewModel.Recipe);
                _recipeRepository.Save();
                return RedirectToAction("Index");
            }
            
            return View();
        }

        public ActionResult Delete(System.Guid id)
        {
            return View(_recipeRepository.Find(id));
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(System.Guid id)
        {
            _recipeRepository.Delete(id);
            _recipeRepository.Save();

            return RedirectToAction("Index");
        }
    }
}